package com.dongfang.coa;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {
    private SensorManager mSensorManager;
    private Sensor mMageticField1, mMageticField2;

    private ImageView ImgCompass;
    private TextView OrientText;
    private TextView accelerometterValue;
    private RotateAnimation myAni = null;
    private float yuanlaijiaodu = 0.0f;

    StringBuilder sb1 = new StringBuilder();
    StringBuffer sb = new StringBuffer();

    Time time = new Time();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.compass);
        OrientText = (TextView) findViewById(R.id.OrientText);
        accelerometterValue = (TextView) findViewById(R.id.accelerometterValue);
        ImgCompass = (ImageView) findViewById(R.id.ivCompass);

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        // 方向
        mMageticField1 = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

        if (mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0) {
            accelerometterValue.setText("加速计没装");
        }
        else {
            mMageticField2 = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mSensorManager.registerListener(this, mMageticField2, SensorManager.SENSOR_DELAY_FASTEST)) {
            accelerometterValue.setText("加速计注册失败");
        }
        mSensorManager.registerListener(this, mMageticField1, SensorManager.SENSOR_DELAY_FASTEST);
    }

    public void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.item1:
            Intent theActivity = new Intent(this, about.class);
            startActivity(theActivity);
            break;
        case R.id.item2:
            mSensorManager.unregisterListener(this);
            finish();
            System.exit(0);
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mSensorManager.unregisterListener(this);
            finish();
            System.exit(0);
        }
        return super.onKeyDown(keyCode, event);
    }

    private void AniRotateImage(float fDegress) {
        myAni = new RotateAnimation(yuanlaijiaodu - fDegress, yuanlaijiaodu - fDegress, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        myAni.setDuration(30);
        myAni.setFillAfter(true);

        ImgCompass.startAnimation(myAni);

        yuanlaijiaodu = fDegress;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            sb1.setLength(0);
            sb1.append("x: ");
            sb1.append(event.values[0]);
            sb1.append("\ny: ");
            sb1.append(event.values[1]);
            sb1.append("\nz: ");
            sb1.append(event.values[2]);
            accelerometterValue.setText(sb1.toString());
            Log.d("MainActivity", sb1.toString());

            sb.append(System.currentTimeMillis()).append(" --> ");
            sb.append(Arrays.toString(event.values)).append("\n");

            if (sb.length() > 1000) {
                handler.sendEmptyMessage(1);
            }

        }

        else if (event.sensor.getType() == 3) {
            int v = (int) event.values[0];
            switch (v) {
            case 0: // North 北
                OrientText.setText("正北");
                break;
            case 90: // East 东
                OrientText.setText("正东");
                break;
            case 180: // South 南
                OrientText.setText("正南");
                break;
            case 270: // West 西
                OrientText.setText("正西");
                break;
            default: {
                // int v = (int)event.values[0];
                if (v > 0 && v < 90) {
                    OrientText.setText("北偏东" + v);
                }
                else if (v > 90 && v < 180) {
                    v = 180 - v;
                    OrientText.setText("南偏东" + v);
                }
                else if (v > 180 && v < 270) {
                    v = v - 180;
                    OrientText.setText("南偏西" + v);
                }
                else if (v > 270 && v < 360) {
                    v = 360 - v;
                    OrientText.setText("北偏西" + v);
                }
                break;
            }
            }

            ((TextView) findViewById(R.id.OrientValue)).setText(event.values[0] + "");
            if (yuanlaijiaodu != -event.values[0])
                AniRotateImage(-event.values[0]);
        }
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 1:
                writeDataToSD();
                break;
            }
        }
    };

    void writeDataToSD() {
        try {
            /* 获取File对象，确定数据文件的信息 */
            File file = new File(Environment.getExternalStorageDirectory(), "text10.txt");

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = sb.toString().getBytes();
                /* 开始写入数据 */
                fos.write(buffer, (int) file.length(), buffer.length);

                /* 关闭流的使用 */
                fos.close();
                Toast.makeText(MainActivity.this, "文件写入成功", 1000).show();
            }

        } catch (Exception ex) {
            Toast.makeText(MainActivity.this, "文件写入失败", 1000).show();
        }
    }

}